package com.yixuan.mt.common.service.impl_mysql;

import com.yixuan.mt.common.entity.Policy;
import com.yixuan.mt.common.entity.User;
import com.yixuan.mt.common.mapper.IdentityMapper;
import com.yixuan.mt.common.request.PostIdentityRequest;
import com.yixuan.mt.common.service.IdentityService;
import com.yixuan.mt.common.service.PoliciesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class IdentityServiceMysqlImpl implements IdentityService {

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    @Autowired
    private IdentityMapper identityMapper;
    @Autowired
    private PoliciesService policiesService;

    @Override
    public void postIdentity(PostIdentityRequest postIdentityRequest) {
        postIdentityRequest.setPassword(passwordEncoder.encode(postIdentityRequest.getPassword()));
        identityMapper.insertIdentity(postIdentityRequest);
    }

    @Override
    public void deleteIdentity(Integer id) {
        identityMapper.deleteIdentity(id);
    }

    @Override
    public void updatePassword(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        identityMapper.updatePassword(user);
    }

    @Override
    public List<User> getIdentityList() {
        return identityMapper.selectIdentityList();
    }

    @Override
    public List<Policy> getUserPoliciesList(Integer id) {
        String policyList = identityMapper.selectUserPolicyList(id);
        // 转成整型数组
        String[] policyListArray = policyList.split(",");
        Integer[] policyListIntArray = new Integer[policyListArray.length];
        for (int i = 0; i < policyListArray.length; i++) {
            policyListIntArray[i] = Integer.parseInt(policyListArray[i]);
        }
        return policiesService.getPoliciesList(policyListIntArray);
    }
}
